package com.kun.util;

import java.io.*;

/**
 * 文件工具类
 * Created by likun on 2016/12/30.
 */
public class FileUtil {

    /**
     * 输入流写入到文件
     * @return 成功返回true，失败返回false
     */
    public static boolean inputStream2File(InputStream inputStream,String filePath){
        FileOutputStream fos=null;
        try {
            creadFolder(filePath);
            fos=new FileOutputStream(filePath);
            int len=0;
            byte[] buff=new byte[1024];
            while ((len=inputStream.read(buff))!=-1){
                fos.write(buff,0,len);
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            if (fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 文所在的文件夹如果不存在则生成文件夹
     *
     * @param outPath 文件路径
     */
    public static void creadFolder(String outPath) {
        File folder = new File(new File(outPath).getParent());
        if (!folder.exists()) {
            folder.mkdirs();
        }
    }

    public static byte[] stream2byte(InputStream inputStream) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n = 0;
        while (-1 != (n = inputStream.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }

    public static String getParentFilePath(String filePath) {
        return new File(filePath).getParentFile().getAbsolutePath();
    }
}
